package api

import (
	"fmt"
	"github.com/gin-gonic/gin"
	gogpt "github.com/sashabaranov/go-gpt3"
)

type CompletionsRequestBody struct {
	Prompt string `json:"question"`
}

//type CreateImageRequestBody struct {
//	Prompt string `json:"description"`
//	N      int8   `json:"num"`
//	Size   string `json:"size"`
//	Format string `json:"format"`
//}

type CreateImageRequestBody struct {
	*gogpt.ImageRequest
}

// Complete question
func ASK(c *gin.Context) {
	var requestbody CompletionsRequestBody
	err := c.BindJSON(&requestbody)
	if err != nil {
		c.JSON(400, gin.H{
			"error":  "Invalid request",
			"reason": "",
		})
		return
	}
	gptRequestBody := gogpt.CompletionRequest{
		Model:            "text-davinci-003",
		Prompt:           requestbody.Prompt,
		MaxTokens:        1024,
		Temperature:      0.7,
		TopP:             1,
		FrequencyPenalty: 0,
		PresencePenalty:  0,
	}

	//get Token
	apiKey, err := GetAPIKey()
	if err != nil {
		c.JSON(503, gin.H{
			"error":  "Failed to get token from CoderUtil!",
			"reason": fmt.Sprintf(err.Error()),
		})
		return
	}

	// create gpt request
	gptClient := gogpt.NewClient(apiKey)
	gptResponse, err := gptClient.CreateCompletion(c, gptRequestBody)
	if err != nil {
		c.JSON(503, gin.H{
			"error":  "Failed to get response from OpenAI",
			"reason": fmt.Sprintf(err.Error()),
		})
		return
	}
	c.JSON(200, gin.H{
		"answer": gptResponse.Choices[0].Text,
	})
	return
}
